<template>
    <el-container class="layout-container" style="height: 100vh">
        <el-aside width="180px">
            <el-scrollbar>
                <el-menu :default-active="activeIndex" :router="true" :unique-opened="true" :collapse-transition="false"
                    background-color="#545c64" text-color="#ffffff" active-text-color="#ffd04b" @select="sideleSelect">
                    <div style="height: 70px; display: flex; justify-content: center; align-items: center;">
                        <span style="font-size: 28px; font-weight: 600; color: #4b81b8;">Admin</span>
                    </div>
                    <el-sub-menu :index="item.id" v-for="(item) in menusData.list" :key="item.id">
                        <template #title>
                            <el-icon>
                                <component :is="item.icon" />
                            </el-icon>
                            {{ item.name }}
                        </template>
                        <el-menu-item v-for="(items) in item.children" :key="items.id" :index="items.path">
                            <el-icon>
                                <component :is="items.icon" />
                            </el-icon>
                            {{ items.name }}
                        </el-menu-item>
                    </el-sub-menu>

                </el-menu>
            </el-scrollbar>
        </el-aside>

        <el-container>
            <el-header>

                <div style="height: 70px; display: flex; align-items: center;">
                    <el-icon :size="32" color="#4b81b8">
                        <Fold />
                    </el-icon>

                    <p style="padding: 10px;"></p>
                    <span class="blink" v-if="istype">您有{{ istype }}订单需要处理！</span>
                   <span class="blink" v-if="isYjtype">您有佣金}订单需要处理！</span>
                </div>



                <div style="padding: 0 10px;">


                    <el-badge is-dot class="item">
                        <el-link type="primary"> Hi，{{ nickname }}</el-link>
                    </el-badge>
                    <span style="padding: 10px;"></span>


                    <el-tooltip effect="dark" content="清理缓存" placement="bottom">
                        <el-button type="success" circle @click="accountCacheClear()">清</el-button>
                    </el-tooltip>

                    <el-tooltip effect="dark" content="修改密码" placement="bottom">
                        <el-button type="primary" circle @click="passwordDialog = true">改</el-button>
                    </el-tooltip>

                    <el-popconfirm title="确定退出登录?" @confirm="adminAccountLoginQuit()">
                        <template #reference>
                            <el-button type="danger" circle>退</el-button>
                        </template>
                    </el-popconfirm>

                </div>
            </el-header>

            <el-main>
                <el-scrollbar>
                    <el-card shadow="always" style="min-height: 93vh;">
                        <RouterView></RouterView>
                    </el-card>
                </el-scrollbar>
            </el-main>
        </el-container>
      <audio ref="sfplayer" src="/mp3/sf.mp3"></audio>
      <audio ref="xfplayer" src="/mp3/xf.mp3"></audio>
      <audio ref="yjplayer" src="/mp3/yj.mp3"></audio>
      <audio ref="jgplayer" src="/mp3/jinggao.mp3"></audio>
    </el-container>


    <!-- 修改密码 -->
    <el-dialog v-model="passwordDialog" title="密码修改" center width="30%" :destroy-on-close="true" @close="handleClose">
        <el-form label-width="100px">
            <el-form-item label="旧密码">
                <el-input v-model="passData.password" placeholder="请输入旧密码" />
            </el-form-item>
            <el-form-item label="新密码">
                <el-input v-model="passData.passwords" placeholder="新密码长度8-16位" />
            </el-form-item>
            <el-form-item label="重复新密码">
                <el-input v-model="passData.passwordss" placeholder="请确认新密码长度8-16位" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="danger" @click="passwordDialog = false">取消保存</el-button>
            <el-button type="primary" @click="accountPassword()">保存修改</el-button>
        </template>
    </el-dialog>
</template>
  
<script setup>

import { ref, reactive, onMounted } from 'vue'
import { useRouter, RouterView } from 'vue-router'
import { request_post } from '@/common/axios/request.js'
import { success, error } from '@/common/tool/message.js'
import { Fold } from '@element-plus/icons-vue'
// 引入 ElNotification
import { ElNotification } from 'element-plus'

const router = useRouter()
const passwordDialog = ref(false)
const activeIndex = ref(window.sessionStorage.getItem('path') || 'admin_index')
const nickname = window.localStorage.getItem('admin_nickname')
const menusData = reactive({ list: [] })
const passData = reactive({
    password: '',
    passwords: '',
    passwordss: '',
})


onMounted(() => {
  if(!window.localStorage.getItem('admin_token')){
    router.push('/admin_login')
    success('请先登录')
    return
  }
    accountMenus()
    // 设置用户交互监听
    setupUserInteraction();
})

const sideleSelect = (keyPath) => {
	if(activeIndex.value == keyPath){
		location.reload()
	}else{
		activeIndex.value = keyPath
		window.sessionStorage.setItem('path', keyPath)
	}
}

function handleClose() {
    passData.password = ''
    passData.passwords = ''
    passData.passwordss = ''
}


// 获取菜单
function accountMenus() {
    if (!window.sessionStorage.getItem('path')) {
        activeIndex.value = 'admin_index'
        window.sessionStorage.setItem('path', 'admin_index')
    }
    request_post('admin_account_menus').then(res => {
        // console.log(res)
        if (res.data.code == 200) {
            menusData.list = res.data.data
            window.localStorage.setItem('menus_data', JSON.stringify(menusData.list))
        } else {
            return error(res.data.msg)
        }
    })
}

// 清理缓存
function accountCacheClear() {
    request_post('admin_account_cache_clear').then(res => {
        if (res.data.code == 200) {
            return success(res.data.msg)
        } else {
            return error(res.data.msg)
        }
    })

}

// 修改密码
function accountPassword() {
    request_post('admin_account_password', passData).then(res => {
        if (res.data.code == 200) {
            passwordDialog.value = !passwordDialog.value

            setTimeout(() => {
                window.localStorage.clear();
                router.push('/admin_login');
            }, 1000)

            return success(res.data.msg)
        } else {
            return error(res.data.msg)
        }
    })

}


// 退出登录
function adminAccountLoginQuit() {

    request_post('admin_account_login_quit').then(res => {
        if (res.data.code == 200) {
            window.localStorage.clear();
            router.push('/admin_login');
            return success(res.data.msg)
        } else {
            return error(res.data.msg)
        }
    })

}
// 添加用户交互标志
const userInteracted = ref(false);

// 监听用户交互
function setupUserInteraction() {
  const handleInteraction = () => {
    if (!userInteracted.value) {
      userInteracted.value = true;
      // 首次交互后初始化音频
      initAudioPlayers();
      // 移除监听器
      document.removeEventListener('click', handleInteraction);
      document.removeEventListener('keydown', handleInteraction);
    }
  }

  // 添加事件监听器
  document.addEventListener('click', handleInteraction);
  document.addEventListener('keydown', handleInteraction);
}

// 初始化音频播放器
function initAudioPlayers() {
  // 首次用户交互后调用，允许后续自动播放
  getWalletStatus();
  getGjOrder();

  // 设置定时器
  setInterval(() => {
    getWalletStatus();
  }, 10000);

  setInterval(() => {
    getGjOrder();
  }, 10000);
}

// 上下分
const istype = ref('');
const isYjtype = ref('');
const sfplayer = ref(null);
const xfplayer = ref(null);
const yjplayer = ref(null);
function getWalletStatus() {

  request_post('admin_wallet_status').then(res => {
    if (res.data.code == 200) {

      if (res.data.data.type) {
        if (res.data.data.type == '1') {
          istype.value = '充值';
          if (userInteracted.value && sfplayer.value) {
            sfplayer.value.play().catch(e => console.log('播放失败:', e));
          }
        } else {
          istype.value = '取款';
          if (userInteracted.value && xfplayer.value) {
            xfplayer.value.play().catch(e => console.log('播放失败:', e));
          }
        }

      } else {
        istype.value = '';
      }
      if (res.data.data.yjType) {
        isYjtype.value = '佣金';
        
        if (userInteracted.value && yjplayer.value) {
          yjplayer.value.play().catch(e => console.log('播放失败:', e));
        }
      } else {
        isYjtype.value = '';
      }
    } else {
      return error(res.data.msg);
    }
  });
}

const jgplayer = ref(null);
const gjId = ref(null);
//获取告警信息
function getGjOrder() {

  request_post('admin_get_users_gj').then(res => {
    if (res.data.code == 200 && res.data.data.length > 0) {

      if (userInteracted.value && jgplayer.value) {
        jgplayer.value.play().catch(e => console.log('播放失败:', e));
      }
      if (gjId.value != res.data.data[0].id) {
        gjId.value = res.data.data[0].id;

        // 关闭所有现有通知，确保只显示一个
        ElNotification.closeAll();
        
        ElNotification({
          title: '警告',
          message: '请注意，有用户下注，赶紧盯盘',
          type: 'warning',
          position: 'bottom-right',
          duration: 0,
          key: 'gj-order-notification', // 添加唯一标识
          onClose: () => {
            request_post('admin_set_users_gj', {id: res.data.data[0].id}).then(res2 => {
              if (res2.data.code == 200) {
                console.log('关闭成功')
              }
            });
          }
        });
      }

    }
  })
}


</script>
  
<style scoped>
.blink {
    color: rgb(0, 255, 255);
    font-size: 16px;
    font-weight: 600;
    animation: blink 1s linear infinite;
}

@keyframes blink {
    0% {
        opacity: 1;
    }

    50% {
        opacity: 1;
    }

    50.01% {
        opacity: 0;
    }

    100% {
        opacity: 0;
    }
}

.layout-container .el-header {
    position: relative;
    background-color: #545c64;
    color: #ffd04b;
}

.layout-container .el-aside {
    color: #ffd04b;
    background-color: #545c64;
}

.layout-container .el-menu {
    border-right: none;
}

.layout-container .el-main {
    padding: 8px;
    background-color: #E9EEF3;
}

.layout-container .el-header {
    height: 70px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>
  